package com.lxy.demo.servlet;

import com.lxy.demo.service.UserService;
import com.lxy.demo.service.UserServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//servlet注解
//urlPatterns映射路径
//initParams初始化参数配置
@WebServlet(name = "MyServlet4",
        urlPatterns = "/MyServlet4" ,
        initParams = {@WebInitParam(name = "encoding" ,value = "utf-8")},
        loadOnStartup = 4)
public class MyServlet4 extends HttpServlet {
    //创建业务层对象
    static UserService userService = new UserServiceImpl();

    String encoding = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        config.getServletContext().setAttribute("count",0);
        encoding =  config.getInitParameter("encoding");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding(encoding);
        resp.setContentType("text/html;charset=utf-8");
        //获取数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            boolean user = userService.findUser(username, password);
            if (user){
                resp.getWriter().write("<script>alert('登录成功!')</script>");
                int count = (int)req.getServletContext().getAttribute("count");
                count++;
                req.getServletContext().setAttribute("count",count);
            }else {
                resp.getWriter().write("<script>alert('登录失败!')</script>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("doGet方法被调用了");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
